<?php
/**
 * 股票实时数据
 * User: Administrator
 * Date: 2015/10/8
 * Time: 8:17
 */

namespace Api\Controller;

class StockController extends BeforController
{
    /**
     * 分时行情
     */
    public function timeline()
    {
        $code = I('stockId', '','trim');
        if (empty($code)) {
            $this->response(['code' => __LINE__, 'msg' => '请输入股票代码'], 'json');
        }
        // 查询股票类型
        $db_stock   = M('Stock');
        $stock_type = $db_stock->where(['code' => $code,'type'=>['in',[0,1,2,3,4,5,15,16]]])->getField(['type']);
        if (in_array($stock_type, [0, 1, 2])) {
            $now_code = 'sh' . $code;
        } elseif (in_array($stock_type, [3, 4, 5,15,16])) {
            $now_code = 'sz' . $code;
        } else {
            $this->response(['code' => __LINE__, 'msg' => '请输入正确的股票代码'], 'json');
        }
        import('Common.Util.Stock');
        $stock              = new \Stock();
        $data               = $stock->GetQuote($now_code);
        $data               = $data[$code];
        $reponse            = [
            'attr01' => $data[4],
            'attr02' => $data[1],
            'attr03' => number_format($data[6]/10000,2,'.','').'万',
            'attr04' => $data[5],
            'arrr05' => 0,
            'attr06' => number_format($data[7]/100000000,2,'.','').'亿'
        ];
        $reponse['buyBean'] = [
            ['buyNum' => $data[8], 'buyPrice' => $data[9]],
            ['buyNum' => $data[10], 'buyPrice' => $data[11]],
            ['buyNum' => $data[12], 'buyPrice' => $data[13]],
            ['buyNum' => $data[14], 'buyPrice' => $data[15]],
            ['buyNum' => $data[16], 'buyPrice' => $data[17]]
        ];
        $reponse['sellBean'] = [
            ['sellNum' => $data[18], 'sellPrice' => $data[19]],
            ['sellNum' => $data[20], 'sellPrice' => $data[21]],
            ['sellNum' => $data[22], 'sellPrice' => $data[23]],
            ['sellNum' => $data[24], 'sellPrice' => $data[25]],
            ['sellNum' => $data[26], 'sellPrice' => $data[27]]
        ];
        $reponse['stockURL']=U('Home/Stock/main', ['code' => $code],'html',true);
        $reponse['stintBuyPrice']=$reponse['stintSellPrice']=$reponse['nowPrice']=$data[3];
        $reponse['priceDiff']=round(($data[3]-$data[2]), 2);
        $reponse['priceRate']=round((($data[3]-$data[2])/$data[2]),4);
        // 初始化
        $reponse['stintBuyNum']=$reponse['isAtten']=$reponse['stintSellNum']=0;
        // 检查是否关注
        $dboptional = M('Optional');
        $isAtten=$dboptional->where(['uid'=>$this->_userinfo['muid'],'code'=>$code])->getField('id');
        $reponse['isAtten']=empty($isAtten)?0:1;
        // 当前用户资金持有量
        $reponse['stintBuyNum'] = $this->_userinfo['bankroll'];
        // 股票持有量
        $dbposition = M('StockPosition');
        $position      = $dbposition->field(['sid','total'])->where([
            'muid'  => $this->_userinfo['muid'],
            'code'  => $code,
            'ctime' => 0
        ])->find();
        if(!empty($position['total'])){
            $dblog = M('StockTradesLog');
            $logs_total = $dblog->where(['spid'=>$position['sid'],'type'=>0,'trtime'=>array('between',array(strtotime(date('Y-m-d')),strtotime(date('Y-m-d 23:59:59'))))])->sum('total');
	    $sell_total = $dblog->where(['spid'=>$position['sid'],'type'=>1])->sum('total');
	    $reponse['stintSellNum'] = $position['total']-$logs_total;
        }
        $this->response(['code' => 0, 'data' => $reponse], 'json');
    }

    public function drop()
    {
        import('Common.Util.Stock');
        $stock = new \Stock();
        $type  = I('post.type', 0, 'int');
        $down  = $stock->GetQuoteList($type, 5014, $OrderType = 0, $PageSize = 10);
        $up    = $stock->GetQuoteList($type, 5014, $OrderType = 1, $PageSize = 10);
        foreach ($up as $key => $value) {
            $value    = explode(',', $value);
            $up[$key] = [
                'stockCode' => $value[1],
                'name'      => $value[2],
                'price'     => $value[5],
                'diffPrice' => round(($value[5] - $value[4]), 2),
                'rate'      => round((($value[5] - $value[4]) / $value[4]), 4)
            ];
        }
        foreach ($down as $key => $value) {
            $value      = explode(',', $value);
            $down[$key] = [
                'stockCode' => $value[1],
                'name'      => $value[2],
                'price'     => $value[5],
                'diffPrice' => round(($value[5] - $value[4]), 2),
                'rate'      => round((($value[5] - $value[4]) / $value[4]), 4)
            ];
        }
        $this->response(['code' => 0, 'data' => ['fallStocks' => $down, 'riseStocks' => $up]], 'json');
    }

    public function grail(){
        import('Common.Util.Stock');
        $stock = new \Stock();
        $data  = $stock->IndexUpdown();
        $this->response(['code' => 0, 'data' => ['list' => $data]], 'json');
    }

    /**
     * 行情大盘 数据来源
     */
    public function gtimeline()
    {
        import('Common.Util.Stock');
        $stock = new \Stock();
        $code  = ['sh1A0001', 'sh1A0002', 'sh1A0003', 'sz399001', 'sz399005', 'sz399006'];
        $types = ['1A0001' => 1, '1A0002' => 2, '1A0003' => 3, '399001' => 4, '399005' => 5, '399006' => 6];
        $data  = $stock->GetQuote($code);
        $lists = [];
        foreach ($data as $k => $v) {
            $val            = ['type' => $types[$k], 'index' => $v[3], 'avaPrice' => round(($v[3] - $v[2]), 2)];
            $val['avaRate'] = round(($v[3] - $v[2]) / $v[2], 4);
            $lists[]        = $val;
        }
        $this->response(['code' => 0, 'data' => ['list' => $lists]], 'json');
    }

    /**
     * 用户发帖
     */
    public function thread(){
        $type= I('post.type',0,'intval');
        $ssid = I('post.ssid',0,'intval');
        $content = I('post.content','','trim');
        $title = I('post.title','','trim');
        if(!in_array($type,[0,1,2,3,4]) || empty($title) || empty($content)){
            $this->response(['code' => __LINE__, 'msg' => '参数不正确'], 'json');
        }
        if($type!=2){
            if(empty($ssid)){
                $this->response(['code' => __LINE__, 'msg' => '参数不正确'], 'json');
            }
        }
        if($type==0){
            // 获取id
            $pid = M('ForumPostTableid')->add(array('pid' => null));
            if($pid%1024){
                M('ForumPostTableid')->delete();
                S('max_post_id', $pid);
            }
            $newthread = [
                'fid' => $ssid,
                'posttableid' => 0,
                'author' => $this->_userinfo['nickname'],
                'authorid' => $this->_userinfo['muid'],
                'subject' => $title,
                'dateline' => time(),
                'lastpost' => time(),
                'lastposter' => $this->_userinfo['nickname'],
            ];
            $tid = M('ForumThread')->data($newthread)->add();
            $newpost=[
                'pid'=>$pid,
                'fid' => $ssid,
                'tid' => $tid,
                'first' => '1',
                'author' => $this->_userinfo['nickname'],
                'authorid' => $this->_userinfo['muid'],
                'subject' => $title,
                'dateline' => time(),
                'message' => $content,
                'useip' => get_client_ip(),
                'invisible' => 1
            ];
            $rep=M('ForumPost')->data($newpost)->add();
            $this->response(['code'=>0,'msg'=>'发帖成功'],'json');
        }
        if($type==1){
            // 观点评论
            $db  = M('PointReply');
            $rep = $db->data(['rid'=>md5($ssid.'_'.$this->_userinfo['muid'].microtime(true)),'mid'=>$ssid,'content'=>$content,'muid'=>$this->_userinfo['muid'],'rtime'=>time(),'addrip'=>get_client_ip()])->add();
            if($rep){
                M('Point')->setInc('reply',1);
                $this->response(['code'=>0,'msg'=>'观点点评成功'],'json');
            }else{
                $this->response(['code'=>__LINE__,'msg'=>'观点点评失败'],'json');
            }
        }
        if(in_array($type,[2,3])){
            $db  = M('Qa');
            $rep = $db->data(['aid'=>$ssid,'qcontent'=>$content,'quid'=>$this->_userinfo['muid'],'qtime'=>time(),'qip'=>get_client_ip()])->add();
            if($rep){
                // todo:推送给相关人员
                $this->response(['code'=>0,'msg'=>'问答发布成功'],'json');
            }else{
                $this->response(['code'=>__LINE__,'msg'=>'问答发布失败'],'json');
            }
        }
        if($type==4){
            $db  = M('VideoReply');
            $rep = $db->data(['rid'=>md5($ssid.'_'.$this->_userinfo['muid'].microtime(true)),'mid'=>$ssid,'content'=>$content,'muid'=>$this->_userinfo['muid'],'rtime'=>time(),'addrip'=>get_client_ip()])->add();
            if($rep){
                // 视频评论加1
                M('Video')->setInc('repcount',1);
                $this->response(['code'=>0,'msg'=>'视频点评成功'],'json');
            }else{
                $this->response(['code'=>__LINE__,'msg'=>'视频点评失败'],'json');
            }
        }
    }
}
